/**
 * Copyright 2013-2015
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.terramagnet.learn.rabbitmq.consumer.framework;

import java.io.Serializable;
import java.util.HashMap;

/**
 *
 * @author lip
 */
public class HashFilePersistent extends FilePersistent<HashMap<String, Serializable>> {

    private HashMap<String, Serializable> data;

    @Override
    protected void fromLoad(HashMap<String, Serializable> data) throws Exception {
        this.data = data;
        afterLoad();
    }

    @Override
    protected HashMap<String, Serializable> forSave() throws Exception {
        beforeShutdown();
        return data;
    }

    protected void afterLoad() {
    }

    protected void beforeShutdown() {
    }

    protected <T extends Serializable> T deserialize(String key) {
        if (!isLoaded()) {
            load();
        }
        if (data == null) {
            return null;
        }
        return (T) data.get(key);
    }

    protected void addSerializable(String key, Serializable value) {
        if (data == null) {
            data = new HashMap<String, Serializable>();
        }
        data.put(key, value);
    }

    protected void removeSerializable(String key) {
        if (data != null) {
            data.remove(key);
        }
    }
}
